﻿#include "cameraworker.h"
#include <QThread>



CameraWorker::CameraWorker(QObject* parent) : QObject(parent)
{
	m_bIsStreaming = false;

}

CameraWorker::~CameraWorker()
{
}
void CameraWorker::Initialize()
{

}

void CameraWorker::start()
{
	quit = false;
	run();
}


void CameraWorker::OnFrameReady(int count) {

}

void CameraWorker::SlotsFrameNums()
{

}


void CameraWorker::run()
{
	int x = 0;
	forever
	{
		if (!pause_status)
		{
			if (quit) break;
			if (CameraGetImageBuffer(m_camera.g_hCamera,&m_camera.g_tFrameHead,&m_camera.g_pRawBuffer,2000) == CAMERA_STATUS_SUCCESS)
			{
				if (m_camera.g_readBuf == NULL)
					return;

				CameraImageProcess(m_camera.g_hCamera, m_camera.g_pRawBuffer, m_camera.g_pRgbBuffer, &m_camera.g_tFrameHead);
				CameraReleaseImageBuffer(m_camera.g_hCamera, m_camera.g_pRawBuffer);




				/*if (quit) break;
				QImage img(g_readBuf, g_W_H_INFO.sensor_width, g_W_H_INFO.sensor_height, QImage::Format_Indexed8);
				img.setColorTable(grayColourTable);
				emit captured(img);*/

			HalconCpp::HObject OutImage;
			try {

				uchar* buff = m_camera.g_pRawBuffer;

				int nHeight = m_camera.g_tFrameHead.iHeight;
				int nWidth = m_camera.g_tFrameHead.iWidth;
				memcpy(m_camera.g_readBuf, m_camera.g_pRgbBuffer, nHeight * nWidth);
				//memcpy(m_camera.g_readBuf, buff, nWidth * nHeight);
			 //   HalconCpp::GenImage1(&OutImage, "byte", nWidth, nHeight, (Hlong)(m_camera.g_W_H_INFO.buffer_size));

				HalconCpp::GenImage1(&OutImage, "byte", nWidth, nHeight, (Hlong)(m_camera.g_readBuf));

			}
			catch (...) {
				qDebug() << "CopyToImage Error:";
			}
			m_cData.Hobj = OutImage;
			m_cData.m_nIndex = m_camera.g_hCamera;
			emit sigAlgStart(m_cData);

			m_camera.g_read_fps++;
			CameraReleaseImageBuffer(m_camera.g_hCamera, m_camera.g_pRawBuffer);
		}
		else {
			qDebug() << "timeout";
			QThread::usleep(1000);
		}
	}
	else QThread::usleep(1000);
	if (quit) break;
	}
}


void CameraWorker::stream()
{
	pause_status = false;
}

void CameraWorker::pause()
{
	pause_status = true;
}

void CameraWorker::stop()
{
	pause_status = false;
	quit = true;
}


